import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:shopping_group/baseblocs/bloc_provider.dart';
import 'package:shopping_group/event/event.dart';
import 'package:shopping_group/http/apis/apis.dart';
import 'package:shopping_group/http/http_request_all.dart';
import 'package:shopping_group/modle/notice/entity/file_keyInfo_entity.dart';
import 'package:shopping_group/modle/notice/entity/save_notices_files_entity.dart';
import 'package:shopping_group/utils/network_utils.dart';
import 'package:shopping_group/utils/object_util.dart';
import 'package:shopping_group/utils/route_util.dart';

class ForumBloc implements BlocBase {
  List<SaveNoticesFilesEntity> _listEntity = [];
  StreamController<Object> _initController = StreamController<Object>();
  StreamSink get initDate => _initController.sink;

  ForumBloc() {
    _initController.stream.listen(initData);
  }

  void initData(data) {
    _listEntity?.clear();
    if (data is Map) {
      BotToast.showLoading();
      if (null != data['photos'] &&
          data['photos'] is List &&
          !ObjectUtil.isEmptyList(data['photos'])) {
        _upPhotos(data);
      } else {
        _initTask(data);
      }
    }
  }

  void _upPhotos(Map data) async {
    List<MultipartFile> _infoList = [];
    List<List<int>> photos = [];
    photos = data['photos'];
    for (List<int> path in photos) {
      MultipartFile multipartFile = MultipartFile.fromBytes(
        path,
        filename: DateTime.now().millisecondsSinceEpoch.toString() + '.png',
        //contentType: MediaType.parse('multipart/form-data'),
      );
      _infoList.add(multipartFile);
    }
    Map<String, dynamic> dataMap = {};
    dataMap['multipartFiles'] = _infoList;
    FormData formData = FormData.fromMap(dataMap);

    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.UP_PHOTO_URL, data: formData, headers: {},
            success: (result) {
          if (null != result) {
            List list = List.from(result);
            for (var item in list) {
              FileKeyInfoEntity params = FileKeyInfoEntity.fromJson(item);
              SaveNoticesFilesEntity entity = SaveNoticesFilesEntity()
                ..notisFileType = 'NFT_IMG'
                ..fileUrl = params.alifileUrl;
              _listEntity.add(entity);
            }
            data['lstNoticesFile'] = _listEntity;
            _initTask(data);
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  void _initTask(data) async {
    FocusScope.of(RouteUtil.navigatorKey.currentContext)
        .requestFocus(FocusNode());
    //BotToast.showLoading();
    NetworkUtils.isNetworkConnected(connectedCallback: (connected) {
      if (!connected) {
        BotToast.showText(text: '网络无法连接');
      } else {
        HttpUtilAll.post(Apis.UP_INFO_URL, data: data, headers: {},
            success: (result) {
          BotToast.closeAllLoading();
          if (null != result) {
            eventBus.fire(RefreshForumEvent());
            BotToast.showText(text: '发布成功');
            RouteUtil.closeView();
          }
        }, error: (errorMsg) {
          BotToast.closeAllLoading();
          // 请求失败返回的错误信息
          BotToast.showText(text: errorMsg);
        });
      }
    });
  }

  @override
  void dispose() {
    _initController?.close();
  }
}
